package com.kaiyidiannao.activity.tour;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.*;
import com.kaiyidiannao.adapter.CommonViewpagerAdapter;
import com.kaiyidiannao.adapter.TourCommentAdapter;
import com.kaiyidiannao.common.BaseActionBarActivity;
import com.kaiyidiannao.common.util.DateTimeUtils;
import com.kaiyidiannao.common.util.UIUitls;
import com.kaiyidiannao.data.DataCenter;
import com.kaiyidiannao.https.HttpUtils;
import com.kaiyidiannao.main.R;
import com.kaiyidiannao.model.bean.Comment;
import com.kaiyidiannao.model.bean.TourBean;
import com.kaiyidiannao.model.req.model.*;
import com.kaiyidiannao.view.ActionBarView;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * Created by david on 24/04/14.
 * 凑对去详情页面
 */
public class TourLineDetailActivity extends BaseActionBarActivity implements Observer, View.OnClickListener {

    private int module_type = 1; //实质是catid
    private String itemid;//商品编号id

    public static int REQUEST_COMMENT_CODE = 1;
    public static int REQUEST_COMMENT_SUB_CODE = 2;

    private TourBean bean = null;

    //view相关
    private TextView title;
    private TextView intro;
    private TextView compnay;
    private LinearLayout traffic1;
    private TextView peopleName_comment;
    private ImageView collect; //关注 作收藏处理
    private ImageView joniUs; //加入
    private ImageView praise;//点赞
    private RelativeLayout layout_comment;//评论包裹层
    private ListView comment_listview;//评论的listview
    private LinearLayout line_wrapping;//旅游线路(时间，地点，花费)
    private TextView gather_time, gather_peopleNum, gather_cost;
    private TextView moreDataButton; //加载更多评论
    private TextView tour_detail_gather_limit_people_num;

    private List<Comment> targetList = DataCenter.tourCommentList; //评论listview
    private TourCommentAdapter adapter;

    private int currentPage = DataCenter.LISTVIEW_DEFAULT_PAGE;
    private String commentResultStr = "";
    private String parentId; //子评论的父评论itemid

    private boolean joinUsFlag, collectFlag, priaseFlag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.tour_line_detail);
        // 添加观察者
        DataCenter.getInstance().addObserver(this);

        module_type = getIntent().getIntExtra("catid", DataCenter.CATID_TOUR_LINE);
        itemid = getIntent().getStringExtra("itemid");
        targetList.clear();
        Log.d("TourLineDetail", module_type + "   " + itemid);
        findViews();
        initViews();
        //处理ActionBar
        findActionBar();
        super.showProgressDialog();
        if (isLogin()) {
            new GetTourDetail(itemid, super.getUserid(), module_type + "").execute();
        } else {
            new GetTourDetail(itemid).execute();
        }
        new GetTourCommentLIst(itemid).execute();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        DataCenter.tourCommentList.clear();
        //删除观察者
        DataCenter.getInstance().deleteObserver(this);
    }

    private void findViews() {
        //八张详情图片
        detailViewPager = (ViewPager) findViewById(R.id.detail_ViewPager);
        this.title = (TextView) findViewById(R.id.tour_detail_title);
        this.compnay = (TextView) findViewById(R.id.tour_detail_compnay);
        this.intro = (TextView) findViewById(R.id.tour_detail_line_into);
        this.collect = (ImageView) findViewById(R.id.tour_detail_focus);
        this.joniUs = (ImageView) findViewById(R.id.tour_line_detail_join_us);
        this.praise = (ImageView) findViewById(R.id.tour_detail_fav);
        this.traffic1 = (LinearLayout) findViewById(R.id.tour_detail_line_traffic_linealyout);
        this.peopleName_comment = (TextView) findViewById(R.id.tour_detail_line_username_or_comment);
        this.layout_comment = (RelativeLayout) findViewById(R.id.tour_commnet_wrapping);
        this.comment_listview = (ListView) findViewById(R.id.tour_comment_listview);
        this.line_wrapping = (LinearLayout) findViewById(R.id.tour_module_gather_wrapping);
        this.gather_time = (TextView) findViewById(R.id.tour_detail_gather_time);
        this.gather_cost = (TextView) findViewById(R.id.tour_detail_gather_cost);
        this.gather_peopleNum = (TextView) findViewById(R.id.tour_detail_gather_people_num);
        this.tour_detail_gather_limit_people_num = (TextView) findViewById(R.id.tour_detail_gather_limit_people_num);
        switch (module_type) {
            case DataCenter.CATID_TOUR_LINE://旅游线路
                this.joniUs.setVisibility(View.VISIBLE);
                findViewById(R.id.tour_detail_compnay_layout).setVisibility(View.VISIBLE);
                break;
            case DataCenter.CATID_TOUR_GATHER://召集
                this.joniUs.setVisibility(View.VISIBLE);
                this.line_wrapping.setVisibility(View.VISIBLE);
                this.traffic1.setVisibility(View.GONE);
                break;
            case DataCenter.CATID_TOUR_SMALL_NOTE://微記
                this.traffic1.setVisibility(View.GONE);
                break;
        }

        this.praise.setOnClickListener(this); //点赞
        this.collect.setOnClickListener(this); //收藏
        this.joniUs.setOnClickListener(this); //加入

        //设置姓名
        String username = "";
        if (isLogin()) {
            username = DataCenter.userBeans.get(0).getUsername();
            username = (username == null) ? "匿名" : username;
        } else {
            username = "游客";
        }
        if (module_type == DataCenter.CATID_TOUR_SMALL_NOTE) { //微记
            username = "评论";
        }
        this.peopleName_comment.setText(username);
    }

    /**
     * 初始化8张详情图片
     */
    private ViewPager detailViewPager;
    private CommonViewpagerAdapter commonViewpagerAdapter;
    private List<View> imageList = new ArrayList<View>();
    private List<String> imageUrlList = new ArrayList<String>();

    private void initViewPage() { // 以前的删除了，解决图片不缓存的问题
        commonViewpagerAdapter = new CommonViewpagerAdapter(TourLineDetailActivity.this, imageList, detailViewPager, imageUrlList);

        for (int i = 0; i < imageUrlList.size(); i++) {
            final int position = i;
            ImageView imageView = (ImageView) getLayoutInflater().inflate(R.layout.common_viewpager_item, null);
            imageLoader.displayImage(imageUrlList.get(i), imageView, super.options, null);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    TourLineDetailActivity.super.startImagePagerActivity(position, bean.getPicture());
                }
            });
            imageList.add(imageView);
        }

        detailViewPager.setAdapter(commonViewpagerAdapter);
    }


    private void initViews() {
        moreDataButton = (TextView) getLayoutInflater().inflate(R.layout.listview_addmore_footer, null);
        moreDataButton.setText("查看更多评论");
        this.comment_listview.addFooterView(moreDataButton);
        moreDataButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                moreDataButton.setText("正在加载...");
                if ("查看更多评论".equals(moreDataButton.getText().toString())) {
                    moreDataButton.setText("查看更多评论");
                } else {
                    //加载更多的评论
                    currentPage++;
                    new GetTourCommentLIst(itemid, currentPage).execute();
                }
            }
        });


        boolean flag = false; //UI区分标示
        if (module_type == DataCenter.CATID_TOUR_SMALL_NOTE) {
            flag = true;
        }
        adapter = new TourCommentAdapter(this, targetList, flag);
        this.comment_listview.setAdapter(adapter);
    }

    private void initViews(TourBean bean) {
        this.title.setText(bean.getTitle());
        this.intro.setText(bean.getIntroduce());
        this.compnay.setText(bean.getCompany());
        this.gather_peopleNum.setText(bean.getTotal());
        if (bean.getPeople() != null) {
            if(bean.getPeople().length() == 9){
                this.tour_detail_gather_limit_people_num.setText("不限");
            }else{
                this.tour_detail_gather_limit_people_num.setText(bean.getPeople());
            }
        }

        this.gather_cost.setText(bean.getCost());
        this.gather_time.setText(DateTimeUtils.timeFormat(bean.getFromtime()) + "-" + DateTimeUtils.timeFormat(bean.getTotime())); // 召集时间段
        ((TextView) findViewById(R.id.tour_detail_line_traffic_textview)).setText(bean.getTraffic());

        if (bean.isIs_praise()) { // 已经点赞过了
            praise.setBackgroundResource(R.drawable.list_collection_block);
            priaseFlag = true;
        } else {
            praise.setBackgroundResource(R.drawable.list_collection_empty);
        }

        if (bean.isIs_fav()) { // 已经收藏
            collect.setBackgroundResource(R.drawable.tour_line_detail_add_focus_);
            collectFlag = true;
        } else {
            collect.setBackgroundResource(R.drawable.tour_line_detail_add_focus);
        }

        if (bean.isIs_join()) { //是否加入
            joniUs.setBackgroundResource(R.drawable.tour_line_detail__join_in_);
            joinUsFlag = true;
        } else {
            joniUs.setBackgroundResource(R.drawable.tour_line_detail__join_in);
        }


        //八张详情图片
        imageUrlList = bean.getPicture2();
        initViewPage();
    }

    /**
     * 显示重新加载页面
     */
    private void showReloadView() {
        findViewById(R.id.tour_detail_scrollview).setVisibility(View.GONE);
        findViewById(R.id.realod_layout).setVisibility(View.VISIBLE);
        findViewById(R.id.reload).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                findViewById(R.id.tour_detail_scrollview).setVisibility(View.INVISIBLE);
                findViewById(R.id.realod_layout).setVisibility(View.VISIBLE);
                if (isLogin()) {
                    new GetTourDetail(itemid, getUserid(), module_type + "").execute();
                } else {
                    new GetTourDetail(itemid).execute();
                }

                new GetTourCommentLIst(itemid).execute();
            }
        });
    }

    // startActivityForResult：启动Activity并等待返回结果，返回时重新onActivityResult方法，接收数据
    // 监听另一个Activity
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) { // 用来判断返回码是否正确，即排除物理键返回空数据
            commentResultStr = data.getStringExtra("result");
            //保存评论到数据库中

            //添加主评论
            //String userid, String itemid, String content
            if (!isLogin()) {
                startLoginOrRegistered();
            }
            showProgressDialog("正在提交评论");
            if (requestCode == REQUEST_COMMENT_CODE) {// 用来区分是否是本Activity发出的通知 (主评论)
                new PostTourCommentAdd(bean.getTitle(), getUserid(), itemid, commentResultStr).execute();
            } else if (requestCode == REQUEST_COMMENT_SUB_CODE) { //(子评论)
                new PostTourCommentAdd(bean.getTitle(), getUserid(), itemid, commentResultStr, parentId).execute();
            }
        }

    }

    /**
     * 跳转到评论输入框界面
     */
    public void startCommentActivity() {
        Intent intent = new Intent(TourLineDetailActivity.this, TourCommentActivity.class);
        startActivityForResult(intent, REQUEST_COMMENT_CODE);
    }

    /**
     * 跳转到评论输入框界面
     *
     * @param parentId
     */
    public void startSubCommentActivity(String parentId) {
        Intent intent = new Intent(TourLineDetailActivity.this, TourCommentActivity.class);
        this.parentId = parentId;
        startActivityForResult(intent, REQUEST_COMMENT_SUB_CODE);
    }

    @Override
    public void update(Observable observable, Object data) {
        DataCenter.flag flag = (DataCenter.flag) data;

        super.closeProgressDialog();
        if (flag == DataCenter.flag.GET_TOUR_DETAIL_SUCCESS) {//详情信息
            bean = (TourBean) DataCenter.bean;
            findViewById(R.id.tour_detail_scrollview).setVisibility(View.VISIBLE);
            if (null != bean) {
                initViews(bean);
            }
        }

        if (flag == DataCenter.flag.GET_TOUR_DETAIL_FAILED) {
            showReloadView();
        }

        if (flag == DataCenter.flag.GET_TOUR_COMMENT_LIST_SUCESS) { //评论列表信息
            moreDataButton.setText("查看更多评论");
            updateCommentList();
        } else if (flag == DataCenter.flag.GET_TOUR_COMMENT_LSIT_NO_MORE_DATA) {
            moreDataButton.setText("查看更多评论");
        }

        if (flag == DataCenter.flag.GET_TOUR_COMMENT_ADD_SUCESS) { //添加评论（顶级评论和二级评论）
            if (DataCenter.code.equals(DataCenter.successFlag)) {
                showToast(DataCenter.msg, "评论发布成功");
                new GetTourCommentLIst(itemid).execute();
            } else {
                showToast(DataCenter.msg, "评论发布失败");
            }
        }

        if (flag == DataCenter.flag.POST_PRAISE_SUCESS) { //点赞成功
            if (DataCenter.code.equals(DataCenter.successFlag)) {
                if (priaseFlag) {//从当前的点赞状态变成没有点赞
                    priaseFlag = false;
                    //取消点赞
                    showToast(R.string.praise_cancle);
                    praise.setBackgroundResource(R.drawable.list_collection_empty);
                } else {
                    priaseFlag = true;
                    praise.setBackgroundResource(R.drawable.list_collection_block);
                    //点赞成功
                    showToast(R.string.praise_add);
                }
            } else {
                showToast(DataCenter.msg, "点赞出现异常");
            }
        }


        if (flag == DataCenter.flag.GetAddMESSAGEINFO_SUCCESS) {//收藏成功,关注成功\
            if (DataCenter.code.equals(DataCenter.successFlag)) {
                if (collectFlag) {//从当前的关注状态变成没有关注
                    collectFlag = false;
                    //取消收藏,关注
                    showToast(R.string.fouces_cancle);
                    collect.setBackgroundResource(R.drawable.tour_line_detail_add_focus);
                } else {
                    collectFlag = true;
                    //收藏成功,关注
                    showToast(R.string.fouces_add);
                    collect.setBackgroundResource(R.drawable.tour_line_detail_add_focus_);
                }
            } else {
                showToast(DataCenter.msg, "关注出现错误");
            }
        }

        if (flag == DataCenter.flag.POST_JOIN_SUCESS) {//加入或删除成功
            if (DataCenter.code.equals(DataCenter.successFlag)) {
                if (joinUsFlag) { //从当前的加入状态变成没有加入
                    joniUs.setBackgroundResource(R.drawable.tour_line_detail__join_in);
                    joinUsFlag = false;//取消加入
                    //取消加入成功
                    showToast(R.string.join_cancle);
                } else {
                    joinUsFlag = true;//加入成功
                    joniUs.setBackgroundResource(R.drawable.tour_line_detail__join_in_);
                    //加入成功
                    showToast(R.string.join_add);
                }
            } else {
                showToast(DataCenter.msg, "加入出现异常");
            }
        }
    }

    private void findActionBar() {
        actionBarView = (ActionBarView) findViewById(R.id.actionbar);
        actionBarView.button_right_icon2.setVisibility(View.VISIBLE);
        actionBarView.button_right_icon2.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.btn_commont));
        actionBarView.button_right_icon2.setOnClickListener(new View.OnClickListener() {  // 跳转到评论页面
            @Override
            public void onClick(View v) {
                //有效性判断
                if (!checkEvent()) {
                    return;
                }
                startCommentActivity();
            }
        });

        switch (module_type) {
            case DataCenter.CATID_TOUR_LINE:
                actionBarView.setTitle("旅游线路详情");
                break;
            case DataCenter.CATID_TOUR_GATHER:
                actionBarView.setTitle("召集详情");
                break;
            case DataCenter.CATID_TOUR_SMALL_NOTE:
                actionBarView.setTitle("微记详情");
                break;
        }
    }

    @Override
    public void onClick(View v) {

        if (!checkEvent()) {
            return;
        }

        showProgressDialog();
        switch (v.getId()) {
            case R.id.tour_detail_fav: //点赞
                handlePraiseButton();
                break;
            case R.id.tour_detail_focus: //关注
                handlefoucusButton();
                break;
            case R.id.tour_line_detail_join_us://加入我们
                switch (module_type) {
                    case DataCenter.CATID_TOUR_GATHER:
//                        if ((Integer.parseInt(bean.getTotal())+1) <= Integer.parseInt(bean.getPeople())) {
//                            joinUsFlag = true;
//                            handleJoinUsButton();
//                        }
//                        if ((Integer.parseInt(bean.getTotal())-1) < Integer.parseInt(bean.getPeople())) {
//                        joinUsFlag = false;
//                        handleJoinUsButton();
//                    }
                        if (Integer.parseInt(bean.getTotal()) < Long.parseLong(bean.getPeople())){
                            handleJoinUsButton();
                        }else if(Integer.parseInt(bean.getTotal()) == Long.parseLong(bean.getPeople())){
                            if (joinUsFlag){
                                handleJoinUsButton();
                            }else{
                                closeProgressDialog();
                                showToast("人数已满，不能加入");
                            }
                        }else{
                            closeProgressDialog();
                            showToast("人数已满，不能加入");
                        }
                        break;
                    case DataCenter.CATID_TOUR_LINE:
                        handleJoinUsButton();
                        break;
                }
                break;
        }

    }

    // 加入我们
    private void handleJoinUsButton() {
        String userid = DataCenter.userBeans.get(0).getUserid();
        //还差一个收藏过的字段，用来判断
        String actoin = "add";
        if (joinUsFlag) {
            actoin = "delete";
        }
        //int catid, String userid, String itemid, String action
        new PostJoinus(module_type, userid, itemid, actoin).execute();
        new GetTourDetail(itemid, getUserid(), module_type + "").execute();
    }

    // 收藏，或者关注（collect收藏处理）
    private void handlefoucusButton() {
        String userid = DataCenter.userLogin.get(0).getUserid();
        String action = "add";
        if (collectFlag) {
            action = "delete";
        }
        new PostAddFavorites(module_type, userid, action, itemid, bean.getTitle()).execute();
    }

    // 处理点赞
    private void handlePraiseButton() {
        //还差一个收藏过的字段，用来判断
        String action = "add";
        if (priaseFlag) {
            action = "delete";
        }
        // module_type 就是catid
        new PostPraise(module_type, getUserid(), itemid, action).execute();
    }

    /**
     * 评论
     */
    private void updateCommentList() {

        if (targetList != null && targetList.size() > 0) {
            findViewById(R.id.tour_comment_no_message).setVisibility(View.INVISIBLE);
            comment_listview.setVisibility(View.VISIBLE);

            adapter.notifyDataSetInvalidated();
            float density = getResources().getDisplayMetrics().density; // 屏幕密度（0.75 / 1.0 / 1.5）
            UIUitls.setListViewHeightBasedOnChildren(comment_listview, (int) (density * 100));
        } else {
            findViewById(R.id.tour_comment_no_message).setVisibility(View.VISIBLE);
            comment_listview.setVisibility(View.INVISIBLE);
        }
    }

    /**
     * 点击按前先进性有效性判断，如果没有登录，没有网，详情加载失败不允许操作
     *
     * @return
     */
    private boolean checkEvent() {
        if (bean == null) {
            showToast("详情加载失败");
            return false;
        }
        if (!isLogin()) {
            startLoginOrRegistered();
            return false;
        }
        if (!HttpUtils.isConnected()) {
            showToast("离线模式，无法操作，请连接网络");
            return false;
        }
        return true;
    }
}